/*
   Copyright (c) 2019 Shanghai Xuanzi Technology Co. Ltd https://xuanzi.ltd
   XZMind is licensed under the Mulan PSL v1.
   You can use this software according to the terms and conditions of the Mulan PSL v1.
   You may obtain a copy of Mulan PSL v1 at:
      http://license.coscl.org.cn/MulanPSL
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
   PURPOSE.
   See the Mulan PSL v1 for more details.

*/

package xuanzi.xzmind.client;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import com.google.gwt.dom.client.Element;
import com.google.gwt.thirdparty.guava.common.io.Files;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;

import sbaike.client.h5.client.Action;
import sbaike.client.h5.client.ElUtils;
import xuanzi.h5.fs.client.PopupMenu;
import xuanzi.h5.fs.core.FileReader;
import xuanzi.h5.fs.core.IFile;
import xuanzi.h5.fs.core.IFileSystem;
import xuanzi.h5.fs.core.Log;
import xuanzi.h5.fs.core.SyncListTask;
import xuanzi.h5.fs.impl.BFile;
import xuanzi.h5.fs.impl.BFileBytes;
import xuanzi.h5.xzviews.client.LabelTextArea;
import xuanzi.h5.xzviews.client.LabelTextEdit;
import xuanzi.h5.xzviews.client.Panel;
import xuanzi.h5.xzviews.client.TextArea;
import xuanzi.h5.xzviews.client.Toast;
import xuanzi.h5.xzviews.client.View;
import xuanzi.h5.xzviews.client.ViewGroup;

/**
 * 导出服务类
 * 
 * @author 彭立铭
 *
 */
public class ExportDocumentService {
	
	protected  final Action reviewHTMLAction = new Action() {
		
		@Override
		public void execute(Element el, Event event) { 
		//	ElUtils printEl = ElUtils.bind(RootPanel.getBodyElement()).createEl("iframe").attr("src",makeURL(editor.getRenderedText()+"<script>print()</script>")).addClass("fs-popup-frame");
			
		}
	};

	XZMindEditor editor;
	
	protected Action downloadMdAction = new Action() {
		
		@Override
		public void execute(Element el, Event event) {
			download(editor.getEditorView().getMdText(), editor.getCurrentFile().getName());
		}
	};
	
	protected Action downloadHTMLAction = new Action() {
		
		@Override
		public void execute(Element el, Event event) {
			
			download(editor.getEditorView().getRenderedText(), editor.getCurrentFile().getName()+".html");
		}
	};

	public ExportDocumentService(XZMindEditor editor) {
		this.editor = editor;
	}
	
	public ExportDocumentService() {
		// TODO Auto-generated constructor stub
	}

	public static native String makeURL(String text)/*-{ 
	  return 'data:text/html;charset=utf-8,' + (encodeURIComponent(text)); 
	}-*/;

	/**
	 * 执行下载文件
	 * @param text	文件内容
	 * @param name	文件名
	 */
	public native void download(String text,String name)/*-{
		 var element = $wnd.document.createElement('a');
		  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
		  element.setAttribute('download', name); 
		  element.style.display = 'none';
		  document.body.appendChild(element); 
		  element.click(); 
		  document.body.removeChild(element); 
	}-*/;
	
	
	public Action downloadAction = new Action() {
		
		@Override
		public void execute(Element el, Event event) {
			PopupMenu pm = new PopupMenu(event);
			pm.addMenuItem("MD源文", downloadMdAction).className="fa fa-file-code-o";
			pm.addMenuItem("渲染文档", downloadHTMLAction ).className="fa fa-file-word-o";
			//pm.addMenuItem("预览文档", reviewHTMLAction ).className="fa fa-file-word-o";
			pm.show();
		}
	};
	
	
	private void doExportHTML(final IFileSystem fs,final List<IFile> files,final String header, final String footer,final String title) { 
		final BFile[] sortlist = new BFile[files.size()];
		for(int i=0;i<files.size();i++) {
			sortlist[i] = (BFile) files.get(i);
		}
		Arrays.sort(sortlist, new Comparator<IFile>() {
			@Override
			public int compare(IFile o1, IFile o2) {
				// TODO Auto-generated method stub
				return o1.getPath().compareTo(o2.getPath());
			}
		});
	 
		files.clear();
		for(int i=0;i<sortlist.length;i++) {
			if(sortlist[i].isFile())
				files.add(sortlist[i]);
		}
	 
		final JSZIP zip = new JSZIP();
		final ElUtils el = ElUtils.bind(RootPanel.getBodyElement());
		final ElUtils renderEl = el.createDiv();
		renderEl.attr("style", "position:fixed;left:200%;right:10%;top:10%;bottom:10px;overflow:auto; ");
		final RenderView rv = new RenderView();
		rv.onLoad(null);
		final ElUtils sidebar = renderEl.createEl("ul").attr("id","xz-doc-sidebar"); 
		 
		renderEl.createDiv().attr("id","xzdoc").createEl("textarea").attr("id", "aa");
		SyncListTask<IFile> tasks = new SyncListTask<IFile>(files) {
			
			protected String safePathName(String path) {
				// TODO Auto-generated method stub
				return path.substring(0,path.length()-3);
			}
			
			
			
			@Override
			public void run(final IFile param, int step, int stepCount) { 
				if(!param.isFile()) {
					sidebar.createEl("li").text((param.getName())) ;
					next();
					return ;
				}
					int num = 1;
					sidebar.clear();
					for(int i=0;i<files.size();i++) {
						IFile file = files.get(i);
						String target = file.getPath().substring(fs.getCurrentPath().length()+1);
						String from = file.getPath().substring(fs.getCurrentPath().length()+1);
						sidebar.createEl("li").createA(safePathName(file.getName())).addClass("fs-file-linkd fs-linked").attr("href",linkedPath(from, target));
						if(file==param) {  
							sidebar.createEl("ul").addClass("xz-leftside").attr("id", "custom-toc-container"); 
						} 
						num++;
					}
					//Toast.text("正在生成 "+param.getName()).loading();
					Toast.text(param.getName()).show();
					fs.readFile(param, new FileReader() {
						
						@Override
						public void result(final BFileBytes fbb) { 
							rv.renderText(renderEl.toElement(), "xzdoc", fbb.getBytes());
							Timer timer = new Timer() { 
								@Override
								public void run() { 
									StringBuffer doc = new StringBuffer();
									doc.append("<html>");
									doc.append("<head>");
									doc.append("\t<title>").append(param.getName().substring(0,param.getName().length()-3) + " - "+title).append("</title>");
									doc.append("\t<link rel=\"stylesheet\" href=\"http://editor.md.ipandao.com/css/editormd.css\">");
									doc.append("</head>");
									doc.append("<body>");
									doc.append(header);
									doc.append(renderEl.toElement().getInnerHTML());
									doc.append(footer);
									doc.append("</body>");
									doc.append("</html>");
									zip.file(param.getPath().replace("/", "_").substring(fs.getCurrentPath().length()+1, param.getPath().length()-3)+".html", doc.toString());
									//Log.log(param.getPath());
									next();
									
								}
							};
							timer.schedule(1000);
						}
					});
				 
			}
			
			private String linkedPath(String from, String target) {
				 
				return  target.replace("/", "_").substring(0,target.length()-3)+(".html");
			}



			@Override
			public void finish() { 
				zip.download();
				renderEl.remove(); 
				 
				Toast.text("生成成功，开始下载").show();;
			}
		};
		tasks.start();
	}
	


	public void exportHTML(final IFileSystem fs,final List<IFile> files,View el) {
		Panel panel = new Panel("导出静态站点") {
			
			LabelTextEdit siteTitle = new LabelTextEdit("站点标题",fs.getCurrentFolder().getName());
			TextArea siteHeader = new LabelTextArea("站点头部代码",
					"<div class=\"xz-doc-header\">\r\n" + 
					"玄子思维导图导出文档\r\n" + 
					"</div>\r\n" + 
					"<style>\r\n" + 
					".xz-doc-header{   position: fixed; height: 50px;   background: #fff; border-bottom: 1px solid #eee; left: 0px; right: 0px; line-height: 47px; top: 0px; z-index: 9999;  font-size: 18px;  text-align: center;} \r\n" + 
					"#xz-doc-sidebar{position: fixed;left:0px;top:0px;bottom:0px;background: #fff;max-width:280px;    min-width: 240px;overflow: auto;  border-right: 1px dotted #ccc;  padding: 16px;}\r\n" + 
					"#xz-doc-sidebar li{list-style: none;} \r\n" + 
					"#xz-doc-sidebar ul a{  font-size:14px;  color: #444;text-decoration: none;}    \r\n" + 
					".editormd-html-preview{margin-top:60px;max-width:680px;margin-left:300px}\r\n" + 
					"#xz-doc-sidebar{position:fixed;left:0px;top:50px;bottom:0px;background: #fff;max-width:280px;overflow: auto}\r\n" + 
					"#xz-doc-sidebar ul{ padding:0px}\r\n" + 
					"#xz-doc-sidebar li{ list-style: none;}\r\n" + 
					"#xz-doc-sidebar ul{ padding-left:16px;list-style: none;text-decoration: none;}\r\n" + 
					"#xz-doc-sidebar a{ font-size:14px; line-height: 180%; color: #444;text-decoration: none;}\r\n" + 
					".fs-file-linkd{font-size:16px;color:#222}\r\n"  
					+ "\n</style>\n"
					).placeholder("eg. <div>网页头部</div>");
			TextArea siteFooter = new LabelTextArea("站点头部代码","").placeholder("eg. <div>网页底部</div>");
			private Action exportAction = new Action() {
				
				@Override
				public void execute(Element el, Event event) {
					// TODO Auto-generated method stub
					doExportHTML(fs,files,siteHeader.getValue(),siteFooter.getValue(),siteTitle.getValue());
				}

				
			};
			@Override
			protected void onCreateBody(ElUtils parent) {
				getMaskEl().addClass("fs-panel-mask");
				add(siteTitle);
				add(siteHeader);
				ElUtils ps = parent.createDiv().attr("style", "padding:8px;padding-left:110px;").createDiv().attr("style", "border: 1px dotted #999;padding:8px;font-size:14px;line-height:160%");
				 
				for(IFile item:files) {
					Log.log(item.getPath());
				
					if(item.isFile()) { 
						ElUtils itemEl =  ps.createDiv();
						itemEl.createSpan("").addClass("fa fa-file");
						itemEl.createSpan(item.getPath());
					} 
				}
				
				add(siteFooter);
			}
			
			@Override
			protected void onCreateTitle(ElUtils titleEl) {
				titleEl.createSpan("").addClass("fa fa-chrome"); 
				super.onCreateTitle(titleEl);
				
			}
			
			@Override
			protected void onCreateFooter(ElUtils parent) {
				parent.createLabel("将把当前文件夹内MD生成静态站点。");
				
				parent.createButton("确 定").addClass("fs-fr").click(exportAction );
			}
			
		};
		panel.show();
		/*
		
		*/
		
	} 

}
